package com.dys.testrelect02;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @className: com.dys.testrelect02.Test2
 * @description: com.dys.testrelect02
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/08/27 下午9:34
 */
public class Test2 {
    /**
     * 这是一个main()方法,是应用程序的入口
     *
     * @param args 方法的形参列表,是一个字符串数组,包含了从命令行传递给程序的参数
     */
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 1.获取字节码信息
        Class<Student> cls = Student.class;

        // 2.通过字节码信息获取构造器
        // getConstructors()只能获取被public修饰的构造器
        Constructor<?>[] constructors = cls.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("--------------------------");
        // getDeclaredConstructors(): 获取运行时类的全部修饰符的构造器
        Constructor<?>[] declaredConstructors = cls.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        System.out.println("=========================");
        // 获取指定的构造器：得到空参构造器
        Constructor<Student> con1 = cls.getConstructor();
        System.out.println(con1);
        // 获取指定的构造器：得到2个参数的构造器
        Constructor<Student> con2 = cls.getConstructor(double.class, double.class);
        System.out.println(con2);

        // 得到1个参数的构造器，并且是private修饰的
        System.out.println("************************");
        Constructor<Student> con3 = cls.getDeclaredConstructor(int.class);
        System.out.println(con3);

        // 获取到构造器后，就可以创建对象了
        System.out.println("------------------------");
        Student s1 = con1.newInstance();
        System.out.println(s1);

        Student s2 = con2.newInstance(180.5, 190.5);
        System.out.println(s2);
        // 私有构造器无法创建对象
        // Student s3 = con3.newInstance(1001);
        // System.out.println(s3);
    }
}
